package com.aji.leather1.service.impl;

import com.aji.leather1.domain.Sep;
import com.aji.leather1.enums.Name;
import com.aji.leather1.mapper.ClassMapper;
import com.aji.leather1.mapper.SepMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.aji.leather1.domain.Leather;
import com.aji.leather1.service.LeatherService;
import com.aji.leather1.mapper.LeatherMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
* @createDate 2025-11-11 11:05:28
*/
@Service
@RequiredArgsConstructor
public class LeatherServiceImpl extends ServiceImpl<LeatherMapper, Leather> implements LeatherService{

    private final LeatherMapper leatherMapper;
    private final SepMapper sepMapper;
    private final ClassMapper classMapper;

    @Override
    public void add(MultipartFile file, String leatherNumber, String pictureUrl) {
        String pattern1 = "^[A-Za-z]+-[0-9]+$";
        String pattern2 = "^[A-Za-z]{3}[0-9]+-[0-9]+$";
        String pattern3 = "^[A-Za-z]+-[A-Za-z]+[0-9]+\\.[0-9]+$";
        String pattern4 = "^[A-Za-z]{2}[0-9]-[0-9]$";

        String originalFilename = file.getOriginalFilename();
        if (originalFilename == null) {
            throw new IllegalArgumentException("文件名不能为空");
        }

        // 去掉扩展名
        String nameWithoutExt = originalFilename.contains(".")
                ? originalFilename.substring(0, originalFilename.lastIndexOf("."))
                : originalFilename;

        Leather leather = new Leather();
        leather.setCreateTime(new Date());
        leather.setLeatherNumber(leatherNumber);
        leather.setPictureUrl(pictureUrl);

        if (nameWithoutExt.matches(pattern1)) {
            String[] parts = nameWithoutExt.split("-");
            String leatherName = Name.valueOf(parts[0]).getCname();
            leather.setLeatherName(leatherName);

            leather.setRepeatGroup(Integer.valueOf(parts[1]));

        } else if (nameWithoutExt.matches(pattern2)) {
            Pattern p = Pattern.compile("^([A-Za-z]{3})([0-9]+)-([0-9]+)$");
            Matcher m = p.matcher(nameWithoutExt);

            if (m.find()) {
                String leatherName = Name.valueOf(m.group(1).substring(0, 2)).getCname();
                leather.setLeatherName(leatherName);
                char c = m.group(1).charAt(2);
                if (Character.isLowerCase(c)) {
                    c = Character.toUpperCase(c);
                }
                long agingType = classMapper.getIdByCode(String.valueOf(c));
                System.out.println(c);
                leather.setAgingType(agingType);
                leather.setDegradationDays(Integer.valueOf(m.group(2)));
                leather.setRepeatGroup(Integer.valueOf(m.group(3)));
            }

        } else if (nameWithoutExt.matches(pattern4)) {
            Pattern p = Pattern.compile("^([A-Za-z]{2}[0-9])-([0-9])$");
            Matcher m = p.matcher(nameWithoutExt);
            if (m.find()) {
                String leatherName = Name.valueOf(m.group(1).substring(0, 2)).getCname();
                leather.setLeatherName(leatherName);
                long agingType = classMapper.getIdByCode(String.valueOf(m.group(1).charAt(2)));
                leather.setAgingType(agingType);
                leather.setRepeatGroup(Integer.valueOf(m.group(2)));
            }

        } else if (nameWithoutExt.matches(pattern3)) {
            Pattern p = Pattern.compile("^([A-Za-z]+)-([A-Za-z]+)([0-9]+)\\.([0-9]+)$");
            Matcher m = p.matcher(nameWithoutExt);
            if (m.find()) {
                String leatherName = Name.valueOf(m.group(1)).getCname();
                leather.setLeatherName(leatherName);
                long agingType = classMapper.getIdByCode(String.valueOf(m.group(2)));
                leather.setAgingType(agingType);
                leather.setAgingDays(Integer.valueOf(m.group(3)));
                leather.setRepeatGroup(Integer.valueOf(m.group(4)));
            }

        } else {
            throw new IllegalArgumentException("文件名格式不符合要求：" + nameWithoutExt);
        }

        leatherMapper.insert(leather);

        try (
                InputStreamReader isr = new InputStreamReader(file.getInputStream(), StandardCharsets.UTF_8);
                BufferedReader br = new BufferedReader(isr)
        ) {
            String line;
            while ((line = br.readLine()) != null) {
                if (line.trim().isEmpty()) continue;

                String[] parts = line.split(",");
                if (parts.length != 2) {
                    throw new IllegalArgumentException("CSV 文件每行必须是两列，用逗号分隔：" + line);
                }

                try {
                    Double first = Double.parseDouble(parts[0].trim());
                    Double second = Double.parseDouble(parts[1].trim());

                    Sep sep = Sep.builder()
                            .x(first)
                            .y(second)
                            .leatherId(leather.getId()).build();

                    sepMapper.insert(sep);
                } catch (NumberFormatException e) {
                    throw new IllegalArgumentException("CSV 中存在非数字内容：" + line);
                }
            }
        } catch (IOException e) {
            throw new RuntimeException("读取 CSV 文件失败", e);
        }
    }
}




